﻿using System.Web;
using Newtonsoft.Json;
using System.Configuration;
using System;
using RN.ERP.Web.PersonService;
using RN.ERP.Web.ModelService;
using Fly.Common.Linq;
using System.Collections.Generic;

namespace RN.ERP.Web.Handlers
{
    /// <summary>
    /// 主要用来短信验证
    /// </summary>
    public class ExpertAccountHandler : BaseHandler, IHttpHandler
    {
        #region 属性和常量

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public HttpContext Context { set; get; }

        /// <summary>
        /// 系统编号
        /// </summary>
        public string SysCode
        {
            get
            {
                return ConfigurationManager.AppSettings["AppId"];
            }
        }

        /// <summary>
        /// 获取验证码的功能编号
        /// </summary>
        private string FunCode
        {
            get
            {
                return HttpContext.Current.Request["funccode"] ?? "";
            }
        }

        /// <summary>
        /// 获取获取验证码的手机号
        /// </summary>
        private string Phone
        {
            get
            {
                return HttpContext.Current.Request["phone"] ?? "";
            }
        }

        /// <summary>
        /// 每天可修改的最大次数
        /// </summary>
        private const int MAX_SENT_TIME = 4;

        #endregion

        public void ProcessRequest(HttpContext hc)
        {
            Context = hc;
            string funcName = hc.Request["func"];
            FuncRoute(funcName);
        }

        /// <summary>
        /// 功能路由
        /// </summary>
        /// <param name="funcName">功能名称</param>
        private void FuncRoute(string funcName)
        {
            switch (funcName)
            {
                case "pwdreset":
                    ResetPwd();
                    break;
                case "getvercode":
                    GetVerCode();
                    break;
                case "getvercode1":
                    PersonService.PersonServiceClient client = new PersonService.PersonServiceClient();
                    ModelService.OperationResult r = JsonConvert.DeserializeObject<ModelService.OperationResult>(client.CheckWorkExperience(UserInfo.CorpUserGuid, UserInfo.CurrentArea));
                    if (!r.Result)
                    {
                        P(JsonConvert.SerializeObject(new { Success = r.Result, Msg = r.Message }));
                        return;
                    }
                    else
                    {
                        var result = JsonConvert.DeserializeObject<ModelService.OperationResult>(client.ExpertMainSpecCheck(UserInfo.CorpUserGuid, UserInfo.CurrentArea));
                        if (!result.Result)
                        {
                            P(JsonConvert.SerializeObject(new { Success = result.Result, Msg = result.Message }));
                            return;
                        }
                        else
                        {
                            GetVerCode();
                        }
                    }
                    break;
                case "checkvercode":
                    CheckVerCode();
                    break;
                case "checkphoneexists":
                    CheckPhoneExists();
                    break;
                case "getExpertInfo":
                    getExpertInfo();
                    break;
                case "changeNaI":
                    changeExpertInfo();
                    break;
                default: break;
            }
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        private void GetVerCode()
        {
            ZtbService.ZtbServiceClient zsc = new ZtbService.ZtbServiceClient();
            object rst = new { Success = false, Msg = "" };
            ////是否要验证手机号在系统中的存在性
            string checkPhoneExists = Context.Request["CheckPhoneExists"] ?? "false";
            string maxSendTimeStr = Context.Request.QueryString["maxsendtime"];
            int _maxSendTime = MAX_SENT_TIME;

            if (!String.IsNullOrEmpty(maxSendTimeStr))
            {
                int.TryParse(maxSendTimeStr, out _maxSendTime);
            }

            ////获取当前已发验证码次数
            int sentCount = zsc.CheckSentCount(Phone, SysCode, FunCode, null, null);

            if (_maxSendTime > sentCount)
            {
                if (checkPhoneExists == "true" && !IsPhoneExists(Phone))
                {
                    rst = new { Success = false, Msg = "没有与该手机号匹配的账户，请确认号码填写是否正确。" };
                }
                else
                {
                    string verCode = zsc.GetPhoneCodeAppoint(Phone, SysCode, FunCode);
                    bool success = !String.IsNullOrEmpty(verCode);
                    rst = new { Success = success, Msg = success ? "" : "验证码获取失败，请重新发送" };
                }
            }
            else
            {
                rst = new { Success = false, Msg = "当前操作的手机验证码发送次数过多，请明天再试" };
            }

            P(JsonConvert.SerializeObject(rst));
        }

        /// <summary>
        /// 密码重置
        /// </summary>
        private void ResetPwd()
        {
            BasicService.BasicServiceClient bsc = new BasicService.BasicServiceClient();
            string phone = Context.Request.Form["phone"];
            string pwd = Context.Request.Form["pwd"];
            bool rst = bsc.ResetPwdByTel(phone, pwd);
            P(JsonConvert.SerializeObject(new { success = rst }));
        }

        /// <summary>
        /// 检验验证码
        /// </summary>
        private void CheckVerCode()
        {
            ZtbService.ZtbServiceClient zsc = new ZtbService.ZtbServiceClient();
            string verCode = Context.Request.QueryString["vercode"];
            string maxSendTimeStr = Context.Request.QueryString["maxsendtime"];
            int _maxSendTime = MAX_SENT_TIME;

            if (!String.IsNullOrEmpty(maxSendTimeStr))
            {
                int.TryParse(maxSendTimeStr, out _maxSendTime);
            }

            //// success:验证码正确 incorrent验证码错误 overcount超出当天规定次数
            string rst = String.Empty;
            string msg = String.Empty;

            ////获取当前已更改密码次数
            int sentCount = zsc.CheckSentCount(Phone, SysCode, FunCode, null, null);

            if (_maxSendTime > sentCount)
            {
                if (zsc.CheckPhoneCodeAppoint(Phone, verCode, SysCode, FunCode))
                {
                    rst = "success";
                }
                else
                {
                    rst = "incorrent";
                    msg = "验证码不正确，或已经超过时限";
                }
            }
            else
            {
                ////超出规定次数
                rst = "overcount";
                msg = "该功能每天最多操作" + _maxSendTime.ToString() + "次，请明天再试";
            }
            P(JsonConvert.SerializeObject(new { result = rst, value = Phone, msg = msg }));
        }

        /// <summary>
        /// 验证手机号
        /// </summary>
        private bool IsPhoneExists(string phone)
        {
            using (PersonServiceClient personServiceClient = new PersonServiceClient())
            {
                QueryPersonInfoCondition condition = new QueryPersonInfoCondition();
                condition.MobileTel = new ParameterValue<string>() { V = phone, O = OptEnum.Equal };
                condition.ClassId = new ParameterValue<int?>() { V = 8065, O = OptEnum.Equal };
                List<QueryPersonInfoCondition> list = new List<QueryPersonInfoCondition>();
                list.Add(condition);
                int empNum = personServiceClient.GetExpertsCount(JsonConvert.SerializeObject(list), string.Empty);
                return empNum > 0;
            }
        }

        private void CheckPhoneExists()
        {
            string phone = Context.Request.QueryString["phone"];
            string rst = JsonConvert.SerializeObject(new { result = IsPhoneExists(phone) });
            P(rst);
        }

        private void getExpertInfo()
        {
            bool ret = false;
            string mobile = string.Empty;
            string idcard = string.Empty;
            string name = string.Empty;
            string phone = Context.Request.QueryString["phone"];
            if (String.IsNullOrEmpty(phone))
            {
                P(JsonConvert.SerializeObject(new { result = ret, name = name, mobile = mobile, idcard = idcard }));
            }
            using (PersonServiceClient personServiceClient = new PersonServiceClient())
            {
                QueryPersonInfoCondition condition = new QueryPersonInfoCondition();
                condition.MobileTel = new ParameterValue<string>() { V = phone, O = OptEnum.Equal };
                condition.ClassId = new ParameterValue<int?>() { V = 8065, O = OptEnum.Equal };
                List<QueryPersonInfoCondition> list = new List<QueryPersonInfoCondition>();
                list.Add(condition);
                tb_Emp_Manager expert = JsonConvert.DeserializeObject<tb_Emp_Manager>(personServiceClient.GetExpertInfo(JsonConvert.SerializeObject(list), string.Empty));
                if (expert != null)
                {
                    ret = true;
                    mobile = expert.MobileTel;
                    idcard = expert.IDCard;
                    name = expert.Name;
                }
            }
            P(JsonConvert.SerializeObject(new { result = ret, name = name, mobile = mobile, idcard = idcard }));
        }

        private void changeExpertInfo()
        {
            bool ret = false;
            string msg = "修改失败";
            string mobile = Context.Request["mobile"];
            string name = Context.Request["name"];
            string idcard = Context.Request["idcard"];
            if (String.IsNullOrEmpty(mobile))
            {
                P(JsonConvert.SerializeObject(new { result = ret, msg = msg }));
            }
            using (PersonServiceClient personServiceClient = new PersonServiceClient())
            {
                QueryPersonInfoCondition condition = new QueryPersonInfoCondition();
                condition.MobileTel = new ParameterValue<string>() { V = mobile, O = OptEnum.NotEqual };
                condition.ClassId = new ParameterValue<int?>() { V = 8065, O = OptEnum.Equal };
                condition.IDCard = new ParameterValue<string>() { V = idcard, O = OptEnum.Equal };
                List<QueryPersonInfoCondition> list = new List<QueryPersonInfoCondition>();
                list.Add(condition);
                int empNum = personServiceClient.GetExpertsCount(JsonConvert.SerializeObject(list), string.Empty);
                if (empNum > 0)
                {
                    msg = "此身份证号码已存在";
                    P(JsonConvert.SerializeObject(new { result = ret, msg = msg }));
                }
            }
            using (PersonServiceClient personServiceClient = new PersonServiceClient())
            {
                QueryPersonInfoCondition condition = new QueryPersonInfoCondition();
                condition.MobileTel = new ParameterValue<string>() { V = mobile, O = OptEnum.Equal };
                condition.ClassId = new ParameterValue<int?>() { V = 8065, O = OptEnum.Equal };
                List<QueryPersonInfoCondition> list = new List<QueryPersonInfoCondition>();
                list.Add(condition);
                tb_Emp_Manager expert = JsonConvert.DeserializeObject<tb_Emp_Manager>(personServiceClient.GetExpertInfo(JsonConvert.SerializeObject(list), string.Empty));
                if (expert != null)
                {
                    if (expert.isFreeze != null && expert.isFreeze >= 1)
                    {
                        msg = "信息只能修改一次,超过变更上限";
                    }
                    else
                    {
                        expert.Name = name;
                        expert.IDCard = idcard;
                        if (expert.isFreeze == null)
                        {
                            expert.isFreeze = expert.isFreeze ?? 1;
                        }
                        else
                        {
                            expert.isFreeze = (byte)(expert.isFreeze + 1);
                        }
                        string str = personServiceClient.EditExpertInfo(JsonConvert.SerializeObject(expert), string.Empty);
                        OperationResult result = JsonConvert.DeserializeObject<OperationResult>(str);
                        ret = result.Result;
                        msg = result.Message;
                    }
                }
            }
            P(JsonConvert.SerializeObject(new { result = ret, msg = msg }));
        }

        /// <summary>
        /// 输出
        /// </summary>
        private void P(string str)
        {
            Context.Response.Write(str);
            Context.Response.Flush();
            Context.Response.End();
        }
    }
}